package org.hk.kg.web.impl;

import java.util.regex.Matcher;
import java.util.regex.Pattern;

import org.hk.kg.exception.EleParserException;
import org.hk.kg.exception.ExceptionPrinter;
import org.hk.kg.utils.StringUtils;
import org.hk.kg.web.BaseAction;
import org.hk.kg.web.HtmlRender;

public class GetterElRender implements HtmlRender {
	private static final Pattern GETTER_PATTER = Pattern.compile("\\$\\((\\w*)\\)");
	public boolean validate(String line) {
		return line.matches(".*\\$\\(\\w*\\).*");
	}

	public String execute(String line, BaseAction context) {
		Matcher matcher = GETTER_PATTER.matcher(line);
		StringBuffer tempLine = new StringBuffer();
		while(matcher.find())
		{
			String methodAttr = matcher.group(1);
			String method = StringUtils.field2Getter(methodAttr);
			try {
				tempLine.append(matcher.replaceAll(context.invoke(method)));
			} catch (EleParserException e) {
				tempLine.append(ExceptionPrinter.printException(e));
			}
		}
		return tempLine.toString();
	}

}
